<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" />
</head>
<style>
    table tbody {
        display: block;
        height: 195px;
        overflow-y: scroll;
    }

    table thead,
    tbody tr {
        display: table;
        width: 100%;
        table-layout: fixed;
    }

    /*table thead {
    width: calc( 100% - 1em )
}*/
</style>

<body>
    <header class="aui-bar aui-bar-nav" style="background-color: #03a9f4;position:fixed;" id="header">
        <a class="aui-pull-left aui-btn" tapmode onclick="closeWin();">
            <span class="aui-iconfont aui-icon-left"></span>
        </a>
        <div class="aui-title" id="title">
            形态转换
        </div>
    </header>
    <div class="aui-content aui-margin-b-15" style="margin-top:50px;">
        <ul class="aui-list aui-form-list">

            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">物料（新）</div>
                    <div class="aui-list-item-input">
                        <input type="text" placeholder="选择/扫描 物料" id="relMrlCode" value="" onclick="getIdSelector();" onfocus="focusFn(this)"/>
                    </div>
                    <i class="aui-input-addon aui-iconfont aui-icon-right" onclick="goSelectMrl()"></i>
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">粉碎料箱号</div>
                    <div class="aui-list-item-input">
                        <input type="text" placeholder="请扫描粉碎料条码" id="boxnum" value="" onclick="getIdSelector();" onfocus="focusFn(this)">
                    </div>
                </div>
            </li>
            <li class="aui-list-item" style="display:none">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">条码</div>
                    <div class="aui-list-item-input">
                        <input type="text" id="tm">
                    </div>
                </div>
            </li>
            <li class="aui-list-item" style="display:none">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">条码ID</div>
                    <div class="aui-list-item-input">
                        <input type="text" id="tmID">
                    </div>
                </div>
            </li>
            <!-- <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">物料号</div>
                    <div class="aui-list-item-input">
                        <input type="text" id="mrlCode" disabled="true" style="background-color:#d0d0d0">
                    </div>
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">批次号</div>
                    <div class="aui-list-item-input">
                        <input type="text" id="lotCode" disabled="true" style="background-color:#d0d0d0">
                    </div>
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">转换数量</div>
                    <div class="aui-list-item-input">
                        <input type="number" id="qty" disabled="true" style="background-color:#d0d0d0">
                    </div>
                </div>
            </li> -->
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">仓库</div>
                    <div class="aui-list-item-input">
                        <input type="text" placeholder="选择/扫描 仓库" id="workCenterCode" value=""
                            onclick="getIdSelector();" onfocus="focusFn(this)"/>
                    </div>
                    <i class="aui-input-addon aui-iconfont aui-icon-right" onclick="goSelectWorkCenter()"></i>
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">库位</div>
                    <div class="aui-list-item-input">
                        <input type="text" placeholder="选择/扫描 库位" id="workCellCode" value=""
                            onclick="getIdSelector();" onfocus="focusFn(this)"/>
                    </div>
                    <i class="aui-input-addon aui-iconfont aui-icon-right" onclick="goSelectWorkCell()"></i>
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">蓝牙设备</div>
                    <select id="bluetooth">
                    </select>
                </div>
            </li>
        </ul>
        <div style="width:100%;margin-top:2%;"></div>
        <div class="aui-btn aui-btn-info aui-btn-block" onclick="bluetoothConnect()">蓝牙连接</div>
        <div style="width:100%;margin-top:2%;"></div>
        <div class="aui-btn aui-btn-info aui-btn-block" onclick="printBad()">转换并打印</div>
        <div style="width:100%;margin-top:2%;"></div>
        <div class="aui-btn aui-btn-info aui-btn-block" onclick="compareToBoxnum()">撤销</div>
        <div style="width:100%;margin-top:2%;"></div>
        <div class="aui-btn aui-btn-info aui-btn-block" onclick="printBd()">转换补打</div>
        <div class="table-responsive" id="appStorage" style="overflow-y:auto;height: 13rem;">
            <table id="tab" class="table table-bordered " style="table-layout: fixed;">
                <thead>
                    <tr id="tr1"
                        style="text-align: center;background-color: #DCE9F2;color: #467aa7;font-family: 微软雅黑;font-size: 13px;font-weight: bold;">
                        <td style="width:40px;"></td>
                        <td style="width:50px;">序号</td>
                        <td style="width:120px;">箱号</td>
                        <td style="width:120px;;">物料号</td>
                        <td style="width:120px;">批次号</td>
                        <td style="width:120px;">转换数量</td>
                        <td style="width:80px;">操作结果</td>
                        <td style="width:60px;">操作信息</td>
                    </tr>
                </thead>
                <tbody id="tbodyHtml"
                    style='text-align: center;color: black;font-size: 12px;background-color: #F5F5F5;'>


                </tbody>
            </table>
        </div>

    </div>

    <footer class="aui-bar aui-bar-tab" id="footer">
        <div class="aui-bar-tab-item" tapmode id="scan" onclick="doScan()">
            <i class="aui-iconfont aui-icon-scan aui-text-epblue" style="font-size: 1.8rem"></i>
        </div>
    </footer>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript">
    //光标所在id
    var idSelector = "";
    var relMrlId = "";
    var relMrlCode = "";
    var relMrlName = "";
    var workCenterGid = ""; //仓库GID
    var workCenterCode = ""; //仓库编码
    var workCenterName = ""; //仓库名称
    var workCellGid = ""; //库位GID
    var workCellCode = ""; //库位编码
    var workCellName = ""; //库位名称

    var arrSave = [];//需要提交的箱信息

    var maxSubmit = 20;

    var transferFormTransType = "c0631";//形态转换类型

    //初始化
    apiready = function () {
        $("#relMrlCode").focus();
        idSelector = "relMrlCode";
        var query = api.pageParam.query;
        maxSubmit=query.maxSubmit;
        transferFormTransType=query.transferFormTransType;
        //获取蓝牙列表
        getBluetoothCombox();
        //查询条码解析规则
        initScanRule();
    }

    // 获取光标所在组件的id
    function getIdSelector() {
        var e = event || window.event;
        var el = e.srcElement || e.target;
        idSelector = el.id;
        $("#" + el.id).select();
    }

    //查询蓝牙设备
    function getBluetoothCombox() {
        var modulePrinterCpcl = api.require('modulePrinterCpcl');
        modulePrinterCpcl.searchBluetooth({}, function (ret, err) {
            if (ret) {
                if (ret.code == "S") {
                    var list = ret.list;
                    var html = "<option value=''>--请选择--</option>";
                    for (var i = 0; i < list.length; i++) {
                        html += "<option value='" + list[i].code + "'>" + list[i].name + "</option>";
                    }
                    $api.html($api.byId("bluetooth"), html);

                    //取缓存中蓝牙设备打印机
                    var bluetooth = localStorage.getItem('bluetooth');
                    if (bluetooth != null && bluetooth != undefined && bluetooth != "") {
                        $("#bluetooth").val(bluetooth);
                    }

                } else {
                    api.toast({
                        msg: ret.message
                    });
                }
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    //蓝牙连接
    function bluetoothConnect() {
        var address = $("#bluetooth").val();
        if (address == null || address == "" || address == undefined) {
            api.toast({
                msg: "请选择蓝牙"
            });
            return;
        }
        var modulePrinterCpcl = api.require('modulePrinterCpcl');
        modulePrinterCpcl.connectBluetooth({
            address: address,
        }, function (ret, err) {
            if (ret) {
                // api.hideProgress();
                if (ret.code == "S") {
                    api.toast({
                        msg: ret.message
                    });
                } else {
                    api.toast({
                        msg: ret.message
                    });
                }
            } else {
                // api.hideProgress();
                alert(JSON.stringify(err));
            }
        });
    }

    //查询扫描规则
    function initScanRule() {
        var serverUrl = localStorage.getItem('serverUrl');
        var un = localStorage.getItem("un");
        var url = serverUrl + "/app/getTmScanRule";
        var data = {
            values: {
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == '0') {
                    scanRule = myobj.scanRule
                } else {
                    api.toast({
                        msg: myobj.message,
                        duration: 6000
                    });
                }
            }
        });
    }


    // //报废数量值改变事件
    // function checkQty() {
    //     var qty = $("#qty").val();
    //     //转移数量非空校验
    //     if (qty == "" || qty == null || qty == undefined) {
    //     } else {
    //         if (parseFloat(qty) <= 0) {
    //             api.toast({
    //                 msg: '数量必须大于0',
    //                 duration: 6000
    //             });
    //             return;
    //         }
    //     }
    // }


    //扫描
    function doScan() {
        var moduleScanner = api.require('moduleScanner');
        var params = {
            top: 150, //扫描窗口的上边距
            width: 250, //扫描窗口的宽
            height: 250, //扫描窗口的高
            useColor: false, //是否使用自己设定的颜色(startColor和endColor),
            //如果不使用设定的颜色就使用默认的那张网格图
            startColor: '#0F08C8FF', //渐变起始颜色
            endColor: '#7F08C8FF', //渐变结束颜色
            animTime: 2200, //扫描动画时间,单位为毫秒
        };
        moduleScanner.toScannerActivityForResult(params, function (ret, err) {
            //alert(ret);扫码的结果都是编码
            //1：仓库
            if (idSelector == 'workCenterCode') {

                $("#workCenterCode").val(ret);
                //查询仓库
                getWorkCenter(ret, idSelector);

                //2:库位
            } else if (idSelector == 'workCellCode') {

                $("#workCellCode").val(ret);
                //查询库位
                getWorkCell(ret, idSelector);

                //扫描条码
            } else if (idSelector == 'relMrlCode') {

                $("#relMrlCode").val(ret);
                getMrl(ret, idSelector);
            } else if (idSelector == 'boxnum') {

                tmSplit(ret);
            }
        });
    }

    //扫描之后条码解析
    function tmSplit(sm) {
        $("#tm").val(sm);
        //直接解析
        if (scanRule == "old") {

            //本地解析
            localAnalyze(sm);

        } else {

            //后台解析
            postAnalyze(sm);
        }
    }

    //本地解析
    function localAnalyze(sm) {
        $("#tm").val(sm)
        var arr = sm.split(",");
        if (arr[1] == null || arr[1] == undefined) {
            $("#mrlCode").val("");
        } else {
            $("#mrlCode").val(arr[1]);
        }
        if (arr[2] == null || arr[2] == undefined) {
            $("#qty").val("");
        } else {
            $("#qty").val(arr[2]);
        }
        if (arr[3] == null || arr[3] == undefined) {
            $("#lotCode").val("");
        } else {
            $("#lotCode").val(arr[3]);
        }
        if (arr[4] == null || arr[4] == undefined) {
            $("#tmID").val("");
        } else {
            $("#tmID").val(arr[4]);
        }
        if (arr[9] == null || arr[9] == undefined) {
            $("#boxnum").val("");
        } else {
            $("#boxnum").val(arr[9]);
        }
        for (var i = 0; i < arrSave.length; i++) {
            if ($("#boxnum").val() == arrSave[i].boxnum) {
                api.toast({
                    msg: '箱号已存在！',
                    duration: 6000
                });
                $("#boxnum").val("")
                return;
            }
            if (arr[1] != arrSave[i].mrlCode) {
                api.toast({
                    msg: '物料号不一致,无法扫描！',
                    duration: 6000
                });
                $("#boxnum").val("")
                return;
            }
        }
        var model = {
            mrlCode: arr[1], //物料号
            lotCode: arr[3], //批次号
            qty: arr[2], //转移数量
            tm: $("#tm").val(), //条码
            boxnum: $("#boxnum").val(), //箱号
            tmID: arr[4], //条码ID
            resultCode: "",
            resultMsg: ""
        }
        if(arrSave.length==maxSubmit){
          api.toast({
            msg:'一次转换最多不能超过'+maxSubmit+'箱',
            duration:3000
          })
          return;
        }
        arrSave.push(model);
        freshTable()


    }

    //后台解析条码
    function postAnalyze(sm) {
        $("#tm").val(sm)
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/analysisBarCodeCommon";
        var data = {
            values: {
                tm: sm, //条码
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                //成功
                if (myobj.code == '0') {

                    var map = myobj.data;
                    for (var key in map) {
                        $("#" + key).val(map[key]);
                    }
                    $("#boxnum").focus();
                    idSelector = "boxnum";
                    //判断箱号是否重复
                    for (var i = 0; i < arrSave.length; i++) {
                        if ($("#boxnum").val() == arrSave[i].boxnum) {
                            api.toast({
                                msg: '箱号已存在！',
                                duration: 6000
                            });
                            $("#boxnum").val("")
                            return;
                        }
                        if (map["mrlCode"] != arrSave[i].mrlCode) {
                            api.toast({
                                msg: '物料号不一致,无法扫描！',
                                duration: 6000
                            });
                            $("#boxnum").val("")
                            return;
                        }
                    }
                    var model = {
                        mrlCode: map["mrlCode"], //物料号
                        lotCode: map["lotCode"], //批次号
                        qty: map["qty"], //转移数量
                        tm: $("#tm").val(), //条码
                        boxnum: $("#boxnum").val(), //箱号
                        tmID: map["tmID"],//条码ID
                        resultCode: "",
                        resultMsg: ""
                    }
                    if(arrSave.length==maxSubmit){
                      api.toast({
                        msg:'一次转换最多不能超过'+maxSubmit+'箱',
                        duration:3000
                      })
                      return;
                    }
                    arrSave.push(model);
                    freshTable()

                } else if (myobj.code == '1') {

                    $("#boxnum").val("");
                    $("#boxnum").select();
                    api.toast({
                        msg: myobj.message,
                        duration: 6000
                    });
                }
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    //1：仓库扫描校验
    function getWorkCenter(code, inputId) {
        var un = localStorage.getItem("un");
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getWorkCenter";
        var data = {
            values: { ////以表单方式提交参数（JSON对象）
                un:un,
                workCenterCode: code,
                mrlCode: "",
                lotCode: "",
                qty: ""
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                //成功
                if (myobj.code == '0') {
                    var list = eval(myobj.list);
                    workCenterGid = list[0].workCenterGid;
                    workCenterCode = list[0].workCenterCode;
                    workCenterName = list[0].workCenterName;
                    document.getElementById(inputId).value = list[0].workCenterCode + ":" + list[0].workCenterName;
                    $("#workCellCode").focus();
                    idSelector = "workCellCode";

                } else {
                    api.toast({
                        msg: myobj.message,
                        duration: 6000
                    });
                    $("#workCenterCode").focus();
                    $("#workCenterCode").select();
                }
            }
        });
    }

    //2：选中仓库
    function goSelectWorkCenter() {
        api.openWin({
            name: 'uwmSelectWorkCenter',
            url: 'uwmSelectWorkCenter.html',
            pageParam: {
                flag: "in",
                name: "uwmMrlSwitch",
                mrlCode: "",
                lotCode: "",
                qty: ""
            }
        });
    }

    //仓库选择后回调函数
    function setWorkCenter(id, code, name) {
        workCenterGid = id;
        workCenterCode = code;
        workCenterName = name;
        //$("#workCenterCode").attr("value",code+":"+name);
        document.getElementById('workCenterCode').value = code + ":" + name;
        $("#workCellCode").focus();
        idSelector = "workCellCode";
    }

    //3；PDA自带扫描回车事件
    $("#workCenterCode").on('keypress', function (e) { //#keyword为input文本框
        var keycode = e.keyCode;
        var sm = $(this).val();
        if (keycode == '13') {
            //仓库编码
            $("#workCenterCode").val(sm);
            // console.log("扫描回车事件：" + sm);
            //校验改箱码是否存在
            getWorkCenter(sm, "workCenterCode");
        }
    });

    //5:库位扫描校验
    function getWorkCell(code, inputId) {
        //扫库位前先扫仓库
        if (inputId == "workCellCode") {
            if (workCenterGid == "" || workCenterGid == null || workCenterGid == undefined) {
                api.toast({
                    msg: "请先选择/扫描 仓库",
                    duration: 6000
                });
                $("#workCellCode").val("");
                workCellCode = "";
                workCellGid = "";
                workCellName = "";
                return;
            }
        }
        var un = localStorage.getItem("un");
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getWorkCell";
        var data = {
            values: {
                flag: "in_rk", //库内库间标识（out_kn库内  out_kj库间,in_rk入库出库）
                workCenterGid: workCenterGid, //仓库GID
                workCellCode: code, //库位编码
                relWorkCellGid: "", //目标库位
                tm: "",
                workCellFlag: "", //原库位目标库位flag
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == '0') {
                    var list = eval(myobj.list);
                    workCellGid = list[0].workCellGid;
                    workCellCode = list[0].workCellCode;
                    workCellName = list[0].workCellName;
                    document.getElementById(inputId).value = list[0].workCellCode + ":" + list[0].workCellName;
                    $("#boxnum").focus();
                    idSelector = "boxnum";

                } else {
                    api.toast({
                        msg: myobj.message,
                        duration: 6000
                    });
                    $("#workCellCode").focus();
                    $("#workCellCode").select();
                }
            }
        });
    }

    //6：选择库位
    function goSelectWorkCell() {
        var tm = $("#tm").val();
        //仓库非空校验
        if (workCenterGid == "" || workCenterGid == null || workCenterGid == undefined) {
            api.toast({
                msg: "请先选择/扫描 仓库",
                duration: 6000
            });
            return;
        }

        api.openWin({
            name: 'uwmSelectWorkCell',
            url: 'uwmSelectWorkCell.html',
            pageParam: {
                flag: "in_rk",
                name: "uwmMrlSwitch",
                tm: tm,
                workCenterGid: workCenterGid,
                relWorkCellGid: "",
                workCellFlag: ""
            }
        });
    }

    //库位选择后回调函数
    function setWorkCell(id, code, name) {
        workCellGid = id;
        workCellCode = code;
        workCellName = name;
        document.getElementById('workCellCode').value = code + ":" + name;
        $("#boxnum").focus();
        var e = "boxnum";
        idSelector = e;
    }

    //7；PDA自带扫描回车事件-库位
    $("#workCellCode").on('keypress', function (e) { //#keyword为input文本框
        var keycode = e.keyCode;
        var sm = $(this).val();
        if (keycode == '13') {
            //仓库编码
            $("#workCellCode").val(sm);
            //校验改箱码是否存在
            getWorkCell(sm, "workCellCode");
        }
    });

    // //条码监听回车事件
    $("#boxnum").on('keypress', function (e) { //#keyword为input文本框
        var keycode = e.keyCode;
        var sm = $(this).val();
        if (keycode == '13') {
            tmSplit(sm);
        }
    });




    //6：选择物料
    function goSelectMrl() {
        api.openWin({
            name: 'uwmSelectMrl',
            url: 'uwmSelectMrl.html',
            pageParam: {
                name: "uwmMrlSwitch"
            }
        });
    }

    //物料选择后回调函数
    function setMrl(id, code, name) {
        relMrlId = id;
        relMrlCode = code;
        relMrlName = name;
        document.getElementById('relMrlCode').value = code + ":" + name;
        $("#boxnum").focus();
    }

    //7；PDA自带扫描回车事件-库位
    $("#relMrlCode").on('keypress', function (e) { //#keyword为input文本框
        var keycode = e.keyCode;
        var sm = $(this).val();
        if (keycode == '13') {
            //物料编码
            $("#relMrlCode").val(sm);
            //校验改箱码是否存在
            getMrl(sm, "relMrlCode");
        }
    });

    //5:库位扫描校验
    function getMrl(code, inputId) {
        var un = localStorage.getItem("un");
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getMdMrlList";
        var data = {
            values: {
                codeQ: code,
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == '0') {
                    var list = eval(myobj.list);
                    if (list.length == 0) {
                        api.toast({
                            msg: "物料不存在",
                            duration: 6000
                        });
                    } else {
                        mrlId = list[0].sysid;
                        mrlCode = list[0].code;
                        mrlName = list[0].name;
                        document.getElementById(inputId).value = list[0].code + ":" + list[0].name;
                        $("#boxnum").focus();
                    }


                } else {
                    api.toast({
                        msg: myobj.message,
                        duration: 6000
                    });
                    $("#relMrlCode").focus();
                    $("#relMrlCode").select();
                }
            }
        });
    }

   //选择原箱进行补打对应转换后的条码
    function printBd(){

      var check = $("input[type='checkbox']:checked");
      var count = 0;
      check.each(function() {
          count++;
      });
      //选中行不为1
      if (count == 0) {
          api.toast({
              msg: '请选择至少一条数据！',
              duration: 6000
          });
          return;
      }
      var list = [];

      check.each(function() { //遍历
          var row = $(this).parent("td").parent("tr");
          var boxnum = row.find("[name='boxnum']").html();

          list.push({
              "boxnum": boxnum
          });
      });

      if(count > maxSubmit){
          api.toast({
            msg: '一次转换补打最多不能超过'+maxSubmit+'箱',
            duration: 6000
          })
        return;
      }
      var address = $("#bluetooth").val();
      localStorage.setItem('bluetooth', address);
      var un = localStorage.getItem("un");
      var serverUrl = localStorage.getItem('serverUrl');
      var url = serverUrl + "/app/uwmMrlSwitchTmBd";
      var data = {
          values: {
              list: JSON.stringify(list),
              un: un
          }
      };
      api.ajax({
          url: url,
          method: 'post',
          dataType: 'json',
          timeout: 60,
          returnAll: false,
          data: data
      }, function (ret, err) {
          if (ret) {
              var data = JSON.stringify(ret);
              var myobj = eval("(" + data + ")");
              if (myobj.code == '0') {
                  api.hideProgress();
                  api.toast({
                      msg: "保存成功",
                      duration: 6000
                  }); //清空表单

                  var json = myobj.json;
                  // var arr = [];
                  // var html = "";
                  // for (var i = 0; i < list.length; i++) {
                  //     var resultCode = "";
                      //返回成功
                      // if (list[i].code == 0) {
                      //     var json = list[i].json;
                          //调用PDA打印
                          printPDA(json, address);
                      // }
                  // }
              } else if (myobj.code == '1') {
                  api.hideProgress();
                  api.toast({
                      msg: myobj.message,
                      duration: 6000
                  });
              }


          }
      });


    }

    //录数打印
    function printBad() {

        var address = $("#bluetooth").val();

        var mrlCode = $("#mrlCode").val();
        //批次号
        var lotCode = $("#lotCode").val();
        //数量
        var qty = $("#qty").val();
        //条码
        var tm = $("#tm").val();
        //箱号
        var boxnum = $("#boxnum").val();
        //条码ID
        var tmID = $("#tmID").val();

        //打印机非空校验
        if (address == null || address == "" || address == undefined) {
            api.toast({
                msg: '请选择打印机!',
                duration: 6000
            });
            return;
        }

        //仓库非空校验
        if (workCenterGid == "" || workCenterGid == null || workCenterGid == undefined) {
            api.toast({
                msg: '请选择/扫描仓库',
                duration: 6000
            });
            return;
        }

        //库位非空校验
        if (workCellGid == "" || workCellGid == null || workCellGid == undefined) {
            api.toast({
                msg: '请选择/扫描库位',
                duration: 6000
            });
            return;
        }

        //物料号非空校验
        if (relMrlCode == null || relMrlCode == "" || relMrlCode == undefined) {
            api.toast({
                msg: '请选择或扫描新物料',
                duration: 6000
            });
            return;
        }

        // //箱码非空校验
        // if (boxnum == "" || boxnum == null || boxnum == undefined) {
        //     api.toast({
        //         msg: '箱号不能为空',
        //         duration: 6000
        //     });
        //     return;
        // }

        // //物料非空校验
        // if (mrlCode == "" || mrlCode == null || mrlCode == undefined) {
        //     api.toast({
        //         msg: '粉碎物料号不能为空',
        //         duration: 6000
        //     });
        //     return;
        // }

        // //批次号非空校验
        // if (lotCode == "" || lotCode == null || lotCode == undefined) {
        //     api.toast({
        //         msg: '批次号不能为空',
        //         duration: 6000
        //     });
        //     return;
        // }

        // //数量非空校验
        // if (qty == "" || qty == null || qty == undefined) {
        //     api.toast({
        //         msg: '请输入转换数量',
        //         duration: 6000
        //     });
        //     return;
        // } else {
        //     if (parseFloat(qty) <= 0) {
        //         api.toast({
        //             msg: '转换数量必须大于0',
        //             duration: 6000
        //         });
        //         return;
        //     }
        // }
        if (arrSave.length == 0) {
            api.toast({
                msg: '请扫描粉碎料箱号',
                duration: 6000
            });
            return;
        }else if(arrSave.length > maxSubmit){
            api.toast({
              msg: '一次转换最多不能超过'+maxSubmit+'箱',
              duration: 6000
            })
          return;
        }

        localStorage.setItem('bluetooth', address);
        // console.log("1111111==:"+JSON.stringify(arrSave));
        var un = localStorage.getItem("un");
        var serverUrl = localStorage.getItem('serverUrl');
        api.showProgress({
            title: '转换中...',
        });
        var url = serverUrl + "/app/uwmMrlSwitchTmCreateSave2";
        var data = {
            values: {
                relMrlId: relMrlId,
                relMrlCode: relMrlCode,
                relMrlName: relMrlName,
                workCenterGid: workCenterGid, //仓库id
                workCellGid: workCellGid, //库位编码
                // mrlCode: mrlCode, //物料号
                // lotCode: lotCode, //批次号
                // qty: qty, //转移数量
                // tm: tm, //条码
                // boxnum: boxnum, //箱号
                // tmID: tmID, //条码ID
                list: JSON.stringify(arrSave),
                transferFormTransType:transferFormTransType,
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 60,
            returnAll: false,
            data: data
        }, function (ret, err) {
          api.hideProgress();
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                var arr = [];
                var html = "";
                if(myobj.code=="0"){
                  api.toast({
                      msg: "转换成功",
                      duration: 6000
                  });
                  
                }else{
                  api.toast({
                      msg: myobj.msg,
                      duration: 6000
                  });
                }
                  var list = myobj.list;
                    for (var i = 0; i < list.length; i++) {
                        var resultCode = "";
                        //返回成功
                        if (list[i].code == 0) {
                            var json = list[i].json;
                            //调用PDA打印
                            printPDA(json, address);
                        }
                        html += "<tr >";
                        html += "<td style='width:40px;'><input name='sub' type='checkbox'/></td>";
                        html += "<td name='seqNo' style='width:50px;'>" + (i + 1) + "</td>";
                        html += "<td name='boxnum' style='width:120px;'>" + list[i].boxnum + "</td>";
                        html += "<td name='mrlCode' style='width:120px;'>" + list[i].mrlCode + "</td>";
                        html += "<td name='lotCode' style='width:120px;'>" + list[i].lotCode + "</td>";
                        html += "<td name='qty' style='width:120px;'>" + list[i].qty + "</td>";
                        if (list[i].code == 0) {
                            resultCode = "S"
                            html += "<td name='resultCode'  style='background-color:green;width:80px;'>" + resultCode + "</td>";
                            html += "<td name='resultMsg' style='background-color:green;width:60px;'>" + list[i].message + "</td>";
                        } else {
                            resultCode = "E"
                            html += "<td name='resultCode' style='background-color:red;width:80px;'>" + resultCode + "</td>";
                            html += "<td name='resultMsg'  style='background-color:red;width:60px;'>" + list[i].message + "</td>";
                        }

                        html += "</tr>";
                        var model = {
                            mrlCode: list[i].mrlCode, //物料号
                            lotCode: list[i].lotCode, //批次号
                            qty: list[i].qty, //转移数量
                            tm: list[i].tm, //条码
                            boxnum: list[i].boxnum, //箱号
                            tmID:  list[i].tmID, //条码ID
                            resultCode: resultCode,
                            resultMsg: list[i].message
                        }
                        arr.push(model);
                    }
                   
                    // console.log("222==:"+JSON.stringify(arr));
                    $api.html($api.byId("tbodyHtml"), html);
                $("#boxnum").val("");
                arrSave = arr
                    if(myobj.code=="0"){
                  //都转换成功则清空列表
                  $api.html($api.byId("tbodyHtml"), "");
                arrSave = [];
                }
                
                // console.log("333==:"+JSON.stringify(arrSave));
            }
        });

    }





    //打印
    function printPDA(json, address) {
        var modulePrinterCpcl = api.require('modulePrinterCpcl');
        //modulePrinterCpcl.printerPlatform({ 2023-05-24 by:gaomq 修改为4*6格式打印
        //modulePrinterCpcl.printTemplateSixLineFourBySixQR({    2023-05-25 gaomq 4*6六行模板改为4*6五行模板
        modulePrinterCpcl.printTemplateFiveLineFourBySixQR({
            json: json, //打印数据JSON
            address: address //蓝牙地址
        }, function (ret, err) {
            if (ret) {
                if (ret.code == "S") {
                    api.toast({
                        msg: "打印成功"
                    });
                } else {
                    api.toast({
                        msg: ret.message
                    });
                }
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    function freshTable() {
        var html = "";
        for (var i = 0; i < arrSave.length; i++) {
            html += "<tr >";
            html += "<td style='width:40px;'><input name='sub' type='checkbox'/></td>";
            html += "<td name='seqNo' style='width:50px;'>" + (i + 1) + "</td>";
            html += "<td name='boxnum' style='width:120px;'>" + arrSave[i].boxnum + "</td>";
            html += "<td name='mrlCode' style='width:120px;'>" + arrSave[i].mrlCode + "</td>";
            html += "<td name='lotCode' style='width:120px;'>" + arrSave[i].lotCode + "</td>";
            html += "<td name='qty' style='width:120px;'>" + arrSave[i].qty + "</td>";
            if (arrSave[i].resultCode == "S") {
                html += "<td name='resultCode'  style='background-color:green;width:80px;'>" + arrSave[i].resultCode + "</td>";
                html += "<td name='resultMsg' style='background-color:green;width:60px;'>" + arrSave[i].resultMsg + "</td>";
            } else {
                html += "<td name='resultCode' style='background-color:red;width:80px;'>" + arrSave[i].resultCode + "</td>";
                html += "<td name='resultMsg'  style='background-color:red;width:60px;'>" + arrSave[i].resultMsg + "</td>";
            }
            html += "</tr>";
        }
        $api.html($api.byId("tbodyHtml"), html);
        $("#boxnum").val("");
    }
    function compareToBoxnum() {
        //选中数据
        var check = $("input[type='checkbox']:checked"); //在table中找input下类型为checkbox属性为选中状态的数据
        var count = 0;
        check.each(function () {
            count++;
        });
        //选中行不为1
        if (count == 0) {
            api.toast({
                msg: '请选择至少一条数据！',
                duration: 6000
            });
            return;
        }
        var list = [];
        var arrSave2 = [];

        check.each(function () { //遍历
            var row = $(this).parent("td").parent("tr");
            var boxnum = row.find("[name='boxnum']").html();
            list.push(boxnum);
        });
        for (var a = 0; a < arrSave.length; a++) {
          if(list.indexOf(arrSave[a].boxnum)<0){
            arrSave2.push(arrSave[a]);
          }
            // for (var i = 0; i < list.length; i++) {
            //   console.log("arrSave["+a+"]:"+arrSave[a].boxnum);
            //   console.log("list["+i+"]:"+list[i].boxnum);
            //     if (arrSave[a].boxnum != list[i].boxnum) {
            //       console.log("put:"+arrSave[a]);
            //         arrSave2.push(arrSave[a])
            //     }
            // }
        }
        arrSave = arrSave2;
        freshTable()

    }



    //订单返回按钮
    function closeWin() {
        api.closeWin({});
    }
    function focusFn(ele){  
        $api.attr(ele,'readonly', 'readonly');
            setTimeout(() => {
            $api.removeAttr(ele,'readonly');
        }, 200);
    };
</script>

</html>
